import Mock from 'mockjs';

Mock.setup({
  timeout: '200-600'
});

// 使用webpack的require.context()遍历所有mock文件
const files = require.context('.', true, /\.js$/);
const configArray = files.keys().reduce((arr, key) => {
  if (key === './index.js') {
    return arr;
  }

  return [...arr, files(key).default];
}, []);

const parseParam = (options) => {
  const { url = '' } = options;
  if (options.type === 'GET' && url.indexOf('?') > -1) {
    const queryString = url.split('?')[1] || '';

    options.query = queryString.split('&').reduce((obj, str) => {
      const [key, value] = str.split('=');
      return {
        ...obj,
        [key]: /^(\d|\.)*$/.test(value) ? parseFloat(value) : value
      };
    }, {});
  }

  return options;
};

// 注册所有的mock服务
configArray.forEach((item) => {
  for (const [path, target] of Object.entries(item)) {
    const protocol = path.split(' ');
    Mock.mock(
      new RegExp('^' + protocol[1]),
      protocol[0],
      options => target(parseParam(options))
    );
  }
});
